package com.edgar;

import com.jfinal.kit.FileKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.SQLException;
import java.util.List;

public class SystemTask implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(SystemTask.class);

    @Override
    public void run() {

        List<FileZone> fileZoneList = FileZone.dao.findAll();
        LOG.info("File zone list {}", fileZoneList);

        Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {

                for (FileZone fileZone : fileZoneList) {
                    LOG.info("Current file zone {}", fileZone);

                    if (fileZone.getInt(FileZone.IS_FINISH) == 1) continue;//如果已经记录完成则执行下一次循环

                    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
                    DateTime deleteDateTime = DateTime.parse(fileZone.getStr(FileZone.DELETE_TIME), dateTimeFormatter);
                    if (deleteDateTime.isBeforeNow()) {

                        //根据区域ID获取文件类列表并删除
                        List<FileBox> fileBoxList = FileBox.dao.findByZoneId(fileZone.getStr(FileZone.ZONE_ID));
                        for (FileBox fileBox : fileBoxList) {
                            LOG.info("Current file box {}", fileBox);
                            File file = new File(fileBox.getStr(FileBox.URL));

                            //如果文件存在则删除
                            if (file.exists()) {
                                try {
                                    FileKit.delete(file);//删除文件
                                } catch (Exception e) {
                                    LOG.error("Delete file {} ", fileBox.getStr(FileBox.URL), e);
                                    return false;
                                }
                            }

                            //更新文件状态
                            fileBox.set(FileBox.IS_DELETE, 1);
                            fileBox.set(FileBox.DELETE_TIME, DateTime.now().toString(Contants.DEFAULT_DATE_FOMATTER));
                            boolean isUpdate = fileBox.update();
                            if (!isUpdate) return false;
                        }

                        fileZone.set(FileZone.IS_FINISH, 1);
                        boolean isFinish = fileZone.update();
                        if (!isFinish) return false;
                    }
                }

                return true;
            }
        });

    }
}
